package com.guhappy.stockutil;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import oracle.sql.ARRAY;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
/**
 * @author  bduan
 */
public class UpdateStockHistr {
    private static final Log log = LogFactory.getLog(UpdateStockHistr.class);
    private static final String SUCESS = "success";
    private static final String ERROR = "error";
 
    /**
	 * 
	 */
	public UpdateStockHistr() {
		
	}

    //This is synched so we only do one request at a time
    //If yahoo doesn't return stock info we will try to return it from the map in memory
    public static void main (String [] args){
        try {
        	
        	List<Object> stockList = new ArrayList<Object>();
        	stockList = GlobalStockHome.updateAllStock("4");
	    	Iterator<Object> it = stockList.iterator();
	    	while (it.hasNext()){
	    		Object[] row = (Object[] )it.next();
	    		String ticker = (String) row[0];
	    		GlobalStock stockInfo = null;
	    		stockInfo = GlobalStockHome.findByTicker(ticker);
	    		
 	    		ArrayList<StockPriceHistr> csvRecords = new ArrayList<StockPriceHistr>();
 	    		CallableStatement cstmt = null;
 	      		oracle.sql.ArrayDescriptor a = null;
 	      		oracle.sql.ArrayDescriptor b = null;
 	      		oracle.sql.ArrayDescriptor c = null;
 	      		java.util.Date datetime=new java.util.Date();  
 	      		java.sql.Date mySqlDate = new java.sql.Date(datetime.getTime());
 	    		
 	      		String result=parseDataFile(csvRecords, ticker);
 	      		if (result.equals("success")){
 	      			Connection oraCon = null;
 	      			try {
 						Class.forName("oracle.jdbc.driver.OracleDriver");
 					} 
 					catch (ClassNotFoundException ex)
 						{}
 					oraCon = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.13:1521:orcl", "guhappy","guhappy");
 					oraCon.setAutoCommit(false);
 	    	   		int size=csvRecords.size();
 	    	   		Object[] s1 = new Object[size];
 	      			Object[] s2 = new Object[size];
 	      			Object[] s3 = new Object[size];
 	      			Object[] s4 = new Object[size];
 	      			Object[] s5 = new Object[size];
 	      			Object[] s6 = new Object[size];
 	      			Object[] s7 = new Object[size];
 	      			Object[] s8 = new Object[size];
 	      			
 	      			for (int i = 0; i < size; i++) {
 	      				StockPriceHistr tempsuppliers= (StockPriceHistr)csvRecords.get(i);
 	      				String uuid = UUID.randomUUID().toString();
 	      				s1[i] =  uuid;
 	      				if (tempsuppliers.getHistory_date()!=null)
	 	   		   		{
	 	   	   				mySqlDate = new java.sql.Date(tempsuppliers.getHistory_date().getTime());
	 	   		   			s2[i] =  mySqlDate;
	 	   		   		}
	 	   	   			s3[i] =  tempsuppliers.getHistory_open();
	 	   	   			s4[i] =  tempsuppliers.getHigh_price();
	 	   	   			s5[i] =  tempsuppliers.getLow_price();
	 	   	   			s6[i] =  tempsuppliers.getHistory_close();
	 	   	   			s7[i] =  tempsuppliers.getVolume();
	 	   	   			s8[i] =  stockInfo.getId();
	 	      			}
 	      				a = oracle.sql.ArrayDescriptor.createDescriptor("I_TABLE", oraCon);
 	      				b = oracle.sql.ArrayDescriptor.createDescriptor("V_TABLE", oraCon);
 	      				c = oracle.sql.ArrayDescriptor.createDescriptor("D_TABLE", oraCon);
 	      				ARRAY s1_test = new ARRAY(b, oraCon, s1);
 	      				ARRAY s2_test = new ARRAY(c, oraCon, s2);
 	      				ARRAY s3_test = new ARRAY(a, oraCon, s3);
 	      				ARRAY s4_test = new ARRAY(a, oraCon, s4);
 	      				ARRAY s5_test = new ARRAY(a, oraCon, s5);
 	      				ARRAY s6_test = new ARRAY(a, oraCon, s6);
 	      				ARRAY s7_test = new ARRAY(a, oraCon, s7);
 	      				ARRAY s8_test = new ARRAY(b, oraCon, s8);
 	      				
 	      				/*
 	      	   			 * (v_1 v_table,v_2 v_table, v_3 i_table, v_4 i_table, v_5 i_table, v_6 i_table, v_7 i_table, v_8 i_table, v_9 v_table, v_10 d_table,v_11 v_table,v_12 v_table,v_13 v_table,v_14 v_table )
 	      				*/
 	      				cstmt = oraCon.prepareCall("{ call pro_forall_insert_stockhistory(?,?,?,?,?,?,?,?) }");
 	      				cstmt.setObject(1, s1_test);
 	      				cstmt.setObject(2, s2_test);
 	      				cstmt.setObject(3, s3_test);
 	      				cstmt.setObject(4, s4_test);
 	      				cstmt.setObject(5, s5_test);
 	      				cstmt.setObject(6, s6_test);
 	      				cstmt.setObject(7, s7_test);
 	      				cstmt.setObject(8, s8_test);
 	      				
 	      				long aaaa = System.currentTimeMillis();
 	      				System.out.println(System.currentTimeMillis());
 	      				cstmt.execute();
 	      				oraCon.commit();
 	      				System.out.println("now");
 	      				System.out.println(System.currentTimeMillis()-aaaa);
 	      				if (oraCon!=null){
	 	     				oraCon.close();
	 	     			}
	 	     			if (cstmt!=null){
	 	     				cstmt.close();
	 	     			}
 	      		}
	    	}
        }
    	catch (Exception ex) {
            System.out.println("Unable to get stockinfo for: " + ex);
        }
     }
    
 	private static String parseDataFile(ArrayList<StockPriceHistr> csvRecords, String ticker) {
 		 try {
			URL yahoofin = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + ticker + "&a=00&b=01&c=1990&d=09&e=19&f=2018&g=d&ignore=.csv");
			 URLConnection yc = yahoofin.openConnection();
			 BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
			 String inputLine;
			 StockPriceHistr aHistr = new StockPriceHistr();
			 CSVParser parser = new CSVParser();
			 inputLine = in.readLine();
			 while (null !=(inputLine = in.readLine()) ) {
				 aHistr = new StockPriceHistr(parser.parse(inputLine));
			     csvRecords.add(aHistr);
			 }
			in.close();
			return SUCESS;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ERROR;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ERROR;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ERROR;
		}
    }
    
}